package ru.amse.jsynchro.net.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import ru.amse.jsynchro.logging.ILogger;

public abstract class Server extends Thread {
    protected ILogger logger;
    protected int port;
    
    public Server(ILogger logger) {
        this.logger = logger;
        port = 12345;
    }
    
    synchronized protected boolean setPort(int port) {
        if (this.port != port) {
            this.port = port;
            return true;
        } else {
            return false;
        }
    }
    
    protected boolean listenToClient() {
        try {
            ServerSocket ss = new ServerSocket(port);
            while (true) {
                logger.info("waiting for connection on port " + port);
                Socket s = ss.accept();
                logger.info("server socket accepted");
                Thread thread = getServerThread(s);
                thread.start();
            }
        } catch (IOException e) {
            logger.exception(e);
            return false;
        }
    }
    
    protected abstract Thread getServerThread(Socket s); 
}
